<template>
  <div>
    <el-table :data="dataList" border>
      <el-table-column prop="name" label="姓名" width="180"></el-table-column>
      <el-table-column prop="phone" label="电话" width="180"></el-table-column>
      <el-table-column prop="gender" label="性别" width="100">
        <template #default="scope">
          <span>{{ scope.row.gender ? '男' : '女' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="availableFrom" label="最早接待时间" width="200"></el-table-column>
      <el-table-column prop="availableUntil" label="最晚接待时间" width="200"></el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button type="primary" @click="makeReservation(scope.row)">预约</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @current-change="handlePageChange"
      :current-page="currentPage"
      :page-size="pageSize"
      layout="total, prev, pager, next"
      :total="total"
    >
    </el-pagination>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dataList: [],
      currentPage: 1,
      pageSize: 15,
      total: 0,
    };
  },
  created() {
    this.fetchFreeNannies();
  },
  methods: {
    handlePageChange(page) {
      this.currentPage = page;
      this.fetchFreeNannies();
    },
    fetchFreeNannies() {
      this.$axios.get('/api/reservation/listIsFree', {
        params: {
          currentPage: this.currentPage,
          pageSize: this.pageSize
        }
      })
      .then(res => {
        if (res.data.code === '001') {
          this.dataList = res.data.data;
          this.total = res.data.total;
        } else {
          this.$notify.error({
            title: '错误',
            message: res.data.msg
          });
        }
      })
      .catch(() => {
        this.$notify.error({
          title: '错误',
          message: '请求失败'
        });
      });
    },
    makeReservation(nanny) {
      const userId = this.$store.getters.getUser.user_id;
      const nannyId = nanny.nannyId;
      if (!nannyId) {
        this.$notify.error({
          title: '错误',
          message: '无法获取育婴师ID'
        });
        return;
      }
      this.$axios.post('/api/reservation/item/admin/save', {
        userId: userId,
        nannyId: nannyId
      })
      .then(res => {
        if (res.data.code === '001') {
          this.$notify.success({
            title: '成功',
            message: res.data.msg
          });
          this.fetchFreeNannies();
        } else {
          this.$notify.error({
            title: '错误',
            message: res.data.msg
          });
        }
      })
      .catch(() => {
        this.$notify.error({
          title: '错误',
          message: '请求失败'
        });
      });
    }
  }
};
</script>
